//
//  IAARTMsgQuery.m
//  iPadAuditAuthorise
//
//  Created by XiangDongMBP on 16/9/19.
//  Copyright © 2016年 XiangDong. All rights reserved.
//

#import "IAARTMsgQuery.h"
#import "IAAUrlProtocolMerge.h"
#import "NSTimer+XDTimer.h"
#import "IAAInfoMsgModel.h"
#import "XDLocalPush.h"

@interface IAARTMsgQuery ()

@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) IAAInfoMsgPromptModel *model;
@property (strong, nonatomic) NSMutableArray<NSDictionary *> *promptMArray;

@end

static NSTimeInterval const kTimerInterval = 10;
static NSString * const kInfoMsgPromptModelFileName = @"infoMsgPrompt";     //!< @"网点号_infoMsgPrompt" 存放再文档目录下
static NSInteger const kMaxPromptMArrayCount = 100;

@implementation IAARTMsgQuery

+ (instancetype)sharedInstance {
    static IAARTMsgQuery *instance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [[IAARTMsgQuery alloc] init];
    });
    
    return instance;
}

- (void)dealloc {
    [_timer invalidate];
    NSLog(@"%s", __FUNCTION__);
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initLogicData];
    }
    return self;
}

- (NSString *)getPromptfilePath {
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName = [NSString stringWithFormat:@"%@_%@", IAA_APP_DELEGATE.organizeId, kInfoMsgPromptModelFileName];
    NSString *promptFilePath = [document stringByAppendingPathComponent:fileName];
    return promptFilePath;
}

- (void)initLogicData {
    NSString *promptFilePath = [self getPromptfilePath];
    NSLog(@"消息提示文件的路径是%@", promptFilePath);
    self.promptMArray = [NSMutableArray arrayWithContentsOfFile:promptFilePath];
    if (!self.promptMArray) {
        self.promptMArray = [NSMutableArray array];
    }
}

- (void)saveLogicDatoToDisk {
    NSString *promptFilePath = [self getPromptfilePath];
    NSLog(@"消息提示文件的路径是%@", promptFilePath);
    [self.promptMArray writeToFile:promptFilePath atomically:YES];
}

- (void)startQuery {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:kTimerInterval block:^(NSTimeInterval time) {
        [weakSelf requestRTMsgQuery];
    } repeats:YES];
}

- (void)stopQuery {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    // 保存到本地
    [self saveLogicDatoToDisk];
}

#pragma mark - 逻辑处理
- (void)processPromptModel:(IAAInfoMsgPromptModel *)model {
    CompletionHandler handle = IAA_APP_DELEGATE.completionHandler;
    NSDictionary *dic = [model yy_modelToJSONObject];
    BOOL isExist = NO;
    for (NSDictionary *item in self.promptMArray) {
        if ([item[@"infoNo"] isEqualToString:dic[@"infoNo"]] && [item[@"infoType"] isEqualToString:dic[@"infoType"]]) {
            isExist = YES;
            break;
        }
    }
    if (!isExist) {
        if (self.promptMArray.count < kMaxPromptMArrayCount) {
            [self.promptMArray addObject:dic];
        } else {
            [self.promptMArray replaceObjectAtIndex:(self.promptMArray.count - 1) withObject:dic];
        }
        NSLog(@"收取的实时消息是新的，需要推送(%@)", dic);
        [XDLocalPush prsentLocalPush:dic];
        if (handle) {   // 如果是background fetch模式
            handle(UIBackgroundFetchResultNewData);
            IAA_APP_DELEGATE.completionHandler = nil;
            [self saveLogicDatoToDisk];     //保存到本地
        }
    } else {
        NSLog(@"收取的实时消息是旧的，不需要推送(%@)", dic);
        if (handle) {   // 如果是background fetch模式
            handle(UIBackgroundFetchResultNoData);
            IAA_APP_DELEGATE.completionHandler = nil;
        }
    }
}

#pragma mark - 网络请求
- (void)requestRTMsgQuery {
    NSString *urlStr = [IAAUrlProtocolMerge appInfoMsgQuery];
    NSDictionary *pars = @{//@"orgNo" : IAA_APP_DELEGATE.organizeId,
                           @"orgNo" : @"10022",
                           @"osName": @"iOS",
                           @"token" : IAA_APP_DELEGATE.token};
    CompletionHandler handle = IAA_APP_DELEGATE.completionHandler;
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"实时请求返回%@", responseObject);
        self.model = [IAAInfoMsgPromptModel yy_modelWithJSON:responseObject];
        if ([self.model.resultCode isEqualToString:IAA_RESULT_CODE_SUC]) {
            [self processPromptModel:self.model];
        } else {
            if (handle) {   // 如果是background fetch模式
                handle(UIBackgroundFetchResultNoData);
                IAA_APP_DELEGATE.completionHandler = nil;
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"实时请求失败%@", error);
        if (handle) {   // 如果是background fetch模式
            handle(UIBackgroundFetchResultFailed);
            IAA_APP_DELEGATE.completionHandler = nil;
        }
    }];
}

@end
